<template>
  <el-dialog :model-value="visible" :draggable="true" :title="dialog.title" width="40%">
    <el-card>
      <el-form ref="erpUnitFormRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="单位名称：">
          <el-input v-model="form.name" />
        </el-form-item>
      </el-form>
    </el-card>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitForm"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { addErpUnit, updateErpUnit } from '@/api/erp/erpUnit';

const props = defineProps(['rowData', 'visible', 'dialog']);
const emit = defineEmits(['update:modelValue', 'loadList']);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const erpUnitFormRef = ref<ElFormInstance>();
const buttonLoading = ref(false);

let form = reactive({
  id: undefined,
  name: undefined
});
const rules = ref({
  id: [{ required: true, message: '不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '单位名称不能为空', trigger: 'blur' }]
});
watch(
  () => props.rowData,
  () => {
    form = { ...props.rowData };
  }
);
/** 数据提交*/
const submitForm = () => {
  erpUnitFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.id) {
        await updateErpUnit(form).finally(() => (buttonLoading.value = false));
      } else {
        await addErpUnit(form).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      emit('update:modelValue', false);
      emit('loadList');
    }
  });
};
</script>
